package com.zhengke.controller.placeOrder;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhengke.common.BaseController;
import com.zhengke.common.object.AjaxDone;
import com.zhengke.common.object.Result;
import com.zhengke.pojo.MallServiceGoods01;
import com.zhengke.pojo.ToBuyMsg;
import com.zhengke.pojo.TvOrder;
import com.zhengke.pojo.TvOrderGoods;
import com.zhengke.pojo.TvUser;
import com.zhengke.service.coolxinService.JfdhService;
import com.zhengke.service.placeOrder.xdService;

@Controller
@RequestMapping("xzxd")
public class xdController extends BaseController{

	@Autowired
	private xdService service ;
	
    @Autowired
    private JfdhService jfservice;
	
	@RequestMapping("xzxd01")
	public String toTree() {
		return "PlaceOrder/xzxd01"; 
	}
	
	
	
	  @RequestMapping("toMsg.do")
	    public String toMsg(String areaId, ModelMap model)  {
	        model.put("areaId",areaId);
	        return "PlaceOrder/xzxd02";
	    }
	
	@RequestMapping("tofindGoods.do")
	@ResponseBody
	public Result queryGoods(String type,String goodsName,String areaId,int page, int limit) {
		  
		System.err.println(areaId+goodsName+type);
		Result rs = service.findGoods(areaId, goodsName, type, page, limit);
		
		  return rs;
	}
	
	
	@RequestMapping("toBuyPage.do")
	public String toBuyPage() {
		
		
		return "PlaceOrder/toBuy";
	}
	
	
	/**
	 *  查看商品详情
	 * @param request
	 * @return
	 * @throws Exception
	 */
		@RequestMapping("toBuyDetail.do")
	    @ResponseBody
	    public AjaxDone toBuyDetail(HttpServletRequest request) throws Exception {
			
			
			
	        String goodsId = request.getParameter("goodsId");
	        String goodsType = request.getParameter("goodsType");
	        System.err.println("goodsId----->"+goodsId);
	        System.err.println("goodsId----->"+goodsType);
	        List<ToBuyMsg> rtnList = service.findGoodsDetile(goodsId, goodsType);
	        if(null == rtnList || rtnList.size() ==0 ){
	            return new AjaxDone("300", "数据异常，请重新操作！","","");
	        }else{
	            return new AjaxDone("200", "查询成功！","",rtnList);
	        }
	    }
	

	    /**
	     * 确定下单
	     * @param request
	     * @return
	     * @throws Exception
	     */
	    @RequestMapping("toBuy.do")
	    @ResponseBody
	    public AjaxDone toBuy(HttpServletRequest request) throws Exception {
	    	 try {
	        String userCardNumber = request.getParameter("tvUserMsg[userCardNumber]");
	        Integer servicePointId = Integer.parseInt(request.getParameter("tvUserMsg[servicePointId]"));//服务点id
	       
	        BigDecimal userBalance = new BigDecimal( request.getParameter("tvUserMsg[userBalance]")); //余额
	        TvUser user = jfservice.queryTvUser(userCardNumber);

	        String goodsId = request.getParameter("toBuyGoodsMsg[goods_id]");
	        String goods_name = request.getParameter("toBuyGoodsMsg[goods_name]");
	        String specifications = request.getParameter("toBuyGoodsMsg[specifications]");
	        short goodsType=Short.parseShort(request.getParameter("toBuyGoodsMsg[goods_type]"));
	        
	        System.err.println(goodsType+"--------------------------_____________________________________________________");
	        //预定限额
	        String goodsDestineQuota = request.getParameter("toBuyGoodsMsg[goods_destine_quota]");
	        //库存
	        String goodsStorage = request.getParameter("toBuyGoodsMsg[goods_storage]");
	        //商品单价
	        BigDecimal goodsPrice = new BigDecimal(request.getParameter("toBuyGoodsMsg[common_price]"));

	        //购买数量
	        String number = request.getParameter("data[number]");
	        //邮费（积分）
	        String shippingFeeExch = request.getParameter("data[shippingFeeExch]");
	        //邮费（￥）
	        BigDecimal shippingFee = new BigDecimal(request.getParameter("data[shippingFee]"));
	        //配送方式 0 配送 1 自取
	        String getWaySelect = request.getParameter("data[getWaySelect]");
	        //赠送积分
	        BigDecimal sendInte = new BigDecimal(request.getParameter("data[sendInte]"));
	        //共需mony
	        BigDecimal exchIntegralAmount = new BigDecimal(request.getParameter("data[exchIntegralAmount]"));

	        //当前日期
	        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
	        String updateTime = df.format(new Date());// new Date()获取当前系统时间
	       
	            /**
	             *构造保存订单信息
	             */
	            TvOrder to = new TvOrder();
	            to.setOrderSn(user.getUserId()+String.format("%013d",(new Date().getTime())));//订单编号
	            to.setUserId(user.getUserId()); //用户id tvn号码
	            to.setUserName(user.getUserName()); //用户名称
	            to.setUserCardNumber(user.getUserCardNumber()); //用户卡号
	            to.setAddTime(updateTime);//生成时间
	            to.setServicePointId(servicePointId);//服务点id
	            to.setReceiverName(user.getUserName());
	            to.setReceiverAddress(user.getAddressDetail());
	            to.setReceiverPhone(user.getUserPhone());
	            to.setReceiveProvinceId(user.getProvinceId());
	            to.setReceiveCityId(user.getCityId());
	            to.setReceiptMethod(Short.parseShort(getWaySelect));//收货方式(0：上门送，1：自取)
	            to.setOrderState((short)10);//订单状态：0:已取消;10(默认):待确认;20:已确认;30:已配货;40:已发货;50:已收款;60:已退货
	            to.setIntegralHandsel(sendInte);//赠送积分
	            to.setShippingFee(shippingFee);
	            /**
	             *构造保存订单商品信息
	             */
	            TvOrderGoods tog = new TvOrderGoods();
	            tog.setGoodsName(goods_name);
	            tog.setGoodsTime(updateTime);
	            tog.setSpecifications(specifications);
	            tog.setGoodsNum(new BigDecimal(number));
	            tog.setServicePointId(servicePointId);
	            tog.setUserId(user.getUserId());
	            tog.setState((short)1);//状态(0：取消，1：确认,2:退货)
	            to.setIsExperie((short)2);//订单类型(0：普通商品,1：体验品,2:积分兑换商品)
	            /*
	            判断是否可以兑换成功
	             */
	            //设置总价（￥）
	            if (getWaySelect.equals("0")){ //配送 ，加运费
	                to.setGoodsAmount(goodsPrice);//商品总价格
	                to.setOrderAmount(exchIntegralAmount);//订单总价格
	            }else {
	                to.setGoodsAmount(goodsPrice);//商品总价格
	                to.setOrderAmount(exchIntegralAmount);//订单总价格
	            }
	            /*
	                bigdemical比较大小用compareTo
	                flag = -1,表示bigdemical1小于bigdemical2
	                flag = 0,表示bigdemical1等于bigdemical2；
	                flag = 1,表示bigdemical1大于bigdemical2；
	             */
	            int flag = (user.getUserBalance()).compareTo(exchIntegralAmount);
	            if(flag == -1){
	                return new AjaxDone("300","下单失败，用户积分不足");
	            }
	            tog.setGoodsPrice(goodsPrice);
	            tog.setGoodsType(goodsType);
	            tog.setGoodsId(Integer.parseInt(goodsId));

	            MallServiceGoods01 msg = new MallServiceGoods01();
	            msg.setServicePointId(servicePointId);
	            msg.setGoodsId(Integer.parseInt(goodsId));
	            msg.setGoodsType(goodsType);
	            msg.setGoodsDestineQuota(Integer.parseInt(goodsDestineQuota)-Integer.parseInt(number));//设置预定限额
	            msg.setGoodsStorage(new BigDecimal(Integer.parseInt(goodsStorage)-Integer.parseInt(number)));//设置库存

	            //下单成功的话，因为是积分兑换，所以只扣除会员积分,加上赠送积分
	            //两个BigDecimal类型相减  bignum1.subtract(bignum2)
	            user.setUserBalance(user.getUserBalance().subtract(exchIntegralAmount));
	            user.setUserIntegral((user.getUserIntegral()).add(sendInte));
	    
	            service.createOrder(to,tog,msg,user);

	            return new AjaxDone("200","下单成功！");
	        } catch (NumberFormatException e) {
	            e.printStackTrace();
	            return new AjaxDone("300","下单失败");
	        }
	    }
	
	
	
	
	
	
	
	
	
	
	
	
}
